require('../../../less/controls/graph.less');
var React = require('react');
var Node = require('./Node');
var Link = require('./Link');

module.exports = React.createClass({
	displayName:'FlowCanvas',
	getInitialState:function(){
		return {

		}
	},
	__initDragDrop: function (target){
        target.ondragover = function(event) {
            event.preventDefault();
			console.log('drag-over');
            this.props.onDragOver && this.props.onDragOver(event);
            return true;
        }.bind(this);

        target.ondragenter = function(event) {
			console.log('drag-enter');
			this.props.onDragEnter && this.props.onDragEnter(event);
            return true;
        }.bind(this);

        target.ondrop = function(event) {
			this.props.onDrop && this.props.onDrop(event, JSON.parse(event.dataTransfer.getData("data")||'{}'));
            return false;
        }.bind(this);
	},
	componentDidMount:function(){
		this._dom = this.getDOMNode();
		this.__initDragDrop(this._dom);
	},
	__onNodeDidMount: function (node, nodeProps, nodeState){
		this._nodes = this._nodes || {};
		this._nodes[nodeProps.id] = node;
	},
	__onNodeDrag: function (){

	},
	__onLinkDidMount: function (link, linkProps){
		var _target = this._nodes[linkProps.target],
			_source = this._nodes[linkProps.source];
		link.setTarget(_target);
		link.setSource(_source);
		link.reset();
	},
	render:function(){
		return (
			<div className="c-flow-canvas" >
				{
					this.props.data.nodes.map(function (node, index){
						return <Node draggable={true} render={this.props.nodeRender} key={index} {...node} onDidMount={this.__onNodeDidMount} onNodeDrag={this.__onNodeDrag}/>;
					}.bind(this))
				}
				{
					this.props.data.links.map(function (node, index){
						return <Link render={this.props.linkRender} key={index} {...node} onDidMount={this.__onLinkDidMount} />;
					}.bind(this))
				}
			</div>
		);
	}
});
